﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BaseController : MonoBehaviour {
    public SpaceDash.Data.Player playerData;
    private new Rigidbody rigidbody;
    public bool isGround = true;
    private Animator animator;
    //public float maxTurnAngle = 45f;
    private void Awake()
    {
        BaseClass.Messenger.AddListener("Jump", Jump);
    }
    // Use this for initialization
    void Start () {
        rigidbody = GetComponent<Rigidbody>();
        animator = GetComponent<Movement>().animator;
    }

    // Update is called once per frame
    void FixedUpdate() {
        if(!animator.GetBool("isCollided"))MoveFront();
        BaseClass.Messenger.Broadcast("RunAni");
    }

    public void MoveFront()
    {
        //施加向前的力
        if(rigidbody.velocity.magnitude < playerData.maxSpeed)
        {
            rigidbody.AddForce(transform.forward * rigidbody.mass * playerData.acceleration);
        }
        //更新速度数据
        playerData.speed = rigidbody.velocity.magnitude;
    }

    public void Jump()
    {
        //播放动画
        BaseClass.Messenger.Broadcast("JumpAni");
        //增加初速度，施加向上的力
        rigidbody.velocity += Vector3.up * playerData.jumpBaseSpeed;
        rigidbody.AddForce(Vector3.up * playerData.jumpForce);
    }

    public void Decelerate()
    {
        rigidbody.AddForce(transform.forward * -10f);
    }

    public void Slide()
    {
        playerData.speed *= 0.5f;
        BaseClass.Messenger.Broadcast("OnSlide");
        Invoke("ResetForwardForce", 2f);
    }

    private void ResetForwardForce()
    {
        playerData.speed *= 2f;
    }

    public void TurnLeft()
    {
        transform.Rotate(Vector3.up * -playerData.turnSensitivity);
        rigidbody.velocity = rigidbody.velocity.magnitude * transform.forward;
    }

    public void TurnRight()
    {
        transform.Rotate(Vector3.up * playerData.turnSensitivity);
        rigidbody.velocity = rigidbody.velocity.magnitude * transform.forward;
    }

    public void OnFallingToFloor()
    {
        BaseClass.Messenger.Broadcast("OnFloorAni");
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Floor"))
        {
            if(isGround == false)
            {
                isGround = true;
                OnFallingToFloor();
            }
        }


        if (collision.gameObject.CompareTag("Barrier"))
        {
            BaseClass.Messenger.Broadcast("CollideAni");
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Floor"))
        {
            isGround = false;
        }
    }
}
